package com.easypay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easypay.util.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 电子协议
 *
 * @date: 2021/11/26 15:33
 * @author: pandans
 */
public class Contract {
    private static final String url = "https://api-test.eycard.cn:9443/EasypayMPSystem/ContractServet";
//	private static final String channelId = "616161621051101";   	// 渠道号
//	private static final String merId = "MER021321051101";    		// 商户号
//	private static final String termId = "TE051101";   		// 终端号
//	private static final String key = "3b4v1c1r37zn7hs2iz47055t3w1ykc21v";      		// 签名的key

    // 北京扫码付
    private static final String channelId = "616161621092200";    // 渠道号
    private static final String merId = "MER021321092200";            // 商户号
    private static final String termId = "TE092200";        // 终端号
    private static final String key = "41bdfiw2d6o1vi2yema0v5vc0x8bom1w3";            // 签名的key


    /**
     * @Title: main
     * @Description:
     * @param args
     * @return: void
     */
    public static void main(String[] args) {
//		test1();// 个人开户      userId： CFC5D50666BE219BE05311016B0A4D22
//		test2();// 企业开户
//		test3();// 发送验证码
//		test4();// 创建合同    3201
//		test5();// 签署合同
//		test6();// 合同查询
//		test7();// 合同下载
    }

    // 封装公共参数
    public static Map<String, String> publicParam() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("channelId", channelId);
        map.put("merId", merId);
        map.put("termId", termId);
        map.put("tradeTrace", RandomUtil.generateMixString(20));// 流水号，每次请求唯一，不要重复
        map.put("version", "1.0");
        return map;
    }

    // 获取head
    public static String getTxTime() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String head = sdf.format(d);
        return head;
    }

    // 个人开户
    public static void test1() {// 908DDF7ED99E129FE05312016B0AD3D8
        Map<String, String> map = publicParam();
        map.put("txCode", "3001");
        JSONObject head = new JSONObject();
        head.put("txTime", getTxTime());
        JSONObject contractBody = new JSONObject();
        contractBody.put("head", head);
        JSONObject person = new JSONObject();
        person.put("personName", "张鑫");
//		person.put("identTypeCode","0");//证件类型编码  --不传时默认为身份证
        person.put("identNo", "150404199903141113");
        person.put("mobilePhone", "18686290191");
        person.put("authenticationMode", "公安部数据联网核查");
        contractBody.put("person", person);
        contractBody.put("notSendPwd", "1");
        map.put("contractBody", contractBody.toJSONString());
        String sign = SignUtil.getSign(map, key);
        map.put("sign", sign);
        System.out.println("请求参数=====>" + map.toString());
        try {
            String str = HttpConnectUtils.sendHttpSRequest(url ,map, "POST", null);
            if (!StringUtils.isBlank(str)) {
                JSONObject json = JSON.parseObject(str);
                String sign1 = json.getString("sign");
                json.remove("sign");
                String sign2 = SignUtil.getSign((Map) json, key);
                System.out.println("sign2=====>" + sign2);
                if (sign2.equals(sign1)) {
                    System.out.println("验签成功");
                } else {
                    System.out.println("验签失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 企业开户
    public static void test2() {
        Map<String, String> map = publicParam();
        map.put("txCode", "3002");
        JSONObject contractBody = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("txTime", getTxTime());
        contractBody.put("head", head);
        JSONObject enterprise = new JSONObject();
        enterprise.put("enterpriseName", "重庆芈琼建筑工程有限公司");
        enterprise.put("identTypeCode", "8");
        enterprise.put("identNo", "91500103MA60HDEJ0H");
        enterprise.put("mobilePhone", "17843504503");
        enterprise.put("landlinePhone", "17843504503");
        enterprise.put("authenticationMode", "公安部数据联网核查");
        contractBody.put("enterprise", enterprise);
        JSONObject enterpriseTransactor = new JSONObject();
        enterpriseTransactor.put("transactorName", "陈慧东");
        enterpriseTransactor.put("identTypeCode", "0");
        enterpriseTransactor.put("identNo", "610102197609073132");
        contractBody.put("enterpriseTransactor", enterpriseTransactor);
        contractBody.put("notSendPwd","1");
        map.put("contractBody", contractBody.toJSONString());
        String sign = SignUtil.getSign(map, key);
        map.put("sign", sign);
        System.out.println("请求参数=====>" + map.toString());
        try {
            String str = HttpConnectUtils.sendHttpSRequest(url ,map, "POST", null);
            if (!StringUtils.isBlank(str)) {
                JSONObject json = JSON.parseObject(str);
                String sign1 = json.getString("sign");
                json.remove("sign");
                String sign2 = SignUtil.getSign((Map) json, key);
                System.out.println("sign2=====>" + sign2);
                if (sign2.equals(sign1)) {
                    System.out.println("验签成功");
                } else {
                    System.out.println("验签失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送验证码 （多方都需要发送验证码）
    public static void test3() {
        Map<String, String> map = publicParam();
        map.put("txCode", "3101");
        JSONObject contractBody = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("txTime", getTxTime());
        contractBody.put("head", head);
        JSONObject proxySign = new JSONObject();
//		proxySign.put("userId", "C65A1DDCB98C6F8DE05311016B0A912C");// 开户时返回 子商户获取验证码
//		proxySign.put("userId", "C66ECD3464FB7105E05311016B0A495E");
//		proxySign.put("userId", "CFC87AC1698336B6E05311016B0A9BC8");
//		proxySign.put("userId", "C27F6607D94B4468E05311016B0A96BC");// szc
//		proxySign.put("tradeTrace", UUID.randomUUID().toString().replace("-", ""));


        proxySign.put("userId", "CFC5D50666BE219BE05311016B0A4D22"); // 北京扫码付
//		proxySign.put("userId", "CFC87AC1698336B6E05311016B0A9BC8"); // 北京扫码付 另一方

        int random = (int) ((Math.random() * 9 + 1) * 10);
        proxySign.put("randomCode", String.valueOf(random));
//		proxySign.put("smsTemplateValue", "https://henantest.eycard.cn:8843/zy/ns/contract?bjMchId=134879");
//		proxySign.put("smsTemplateId", "01");
        contractBody.put("proxySign", proxySign);
        map.put("contractBody", contractBody.toJSONString());
        String sign = SignUtil.getSign(map, key);
        map.put("sign", sign);
        System.out.println("请求参数=====>" + map.toString());
        try {
            String str = HttpConnectUtils.sendHttpSRequest(url ,map, "POST", null);
            if (!StringUtils.isBlank(str)) {
                JSONObject json = JSON.parseObject(str);
                String sign1 = json.getString("sign");
                json.remove("sign");
                String sign2 = SignUtil.getSign((Map) json, key);
                System.out.println("sign2=====>" + sign2);
                if (sign2.equals(sign1)) {
                    System.out.println("验签成功");
                } else {
                    System.out.println("验签失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 创建合同 3201
    public static void test4() {
        Map<String, String> map = publicParam();
        map.put("txCode", "3201");
        JSONObject contractBody = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("txTime", getTxTime());   // 交易时间
        contractBody.put("head", head);

        // note
        JSONObject note = new JSONObject();
        int random = (int) ((Math.random() * 9 + 1) * 10);
        note.put("randomCode", random + "");
        note.put("checkCode", "000000");// 验证码
        contractBody.put("note", note);

        JSONObject createContract = new JSONObject();
        createContract.put("templateId", "ZY_1745");// 模板编号

        JSONObject textValueInfo = new JSONObject();

        textValueInfo.put("1", "nnnn");
        textValueInfo.put("2", "22222222222222");
        textValueInfo.put("3", "333333333333");



//		textValueInfo.put("merName", "芸券科技(上海)有限公司");
//		textValueInfo.put("merLegal", "李四");
//		textValueInfo.put("merAddr", "上海市延安西路1612号");
//		textValueInfo.put("ysFilialeName","易生支付有限公司");
//		textValueInfo.put("ysMerLegal","刘鹏");
//		textValueInfo.put("ysMerAddr","上海市静安区1612号");

//		textValueInfo.put("saleName1", "芸券科技(上海)有限公司");
//		textValueInfo.put("buyName1", "李四");
//		textValueInfo.put("3", "上海市延安西路1612号");
//		textValueInfo.put("4","测试公司");
//		textValueInfo.put("5","王五");
//		textValueInfo.put("6","上海市静安区1612号");




        createContract.put("textValueInfo", textValueInfo);


        JSONArray signInfos = new JSONArray();

        JSONObject signInfo = null;
        signInfo = new JSONObject();
        signInfo.put("userId", "CFC5D50666BE219BE05311016B0A4D22");// userid  开户时返回的
        signInfo.put("authorizationTime", getTxTime());// 获取验证码时间
        signInfo.put("location", "127.0.0.1");// IP地址
        signInfo.put("signLocation", "Signature1");// 签名域的标签值
        signInfo.put("projectCode", "123");// 项目编号， （项目编号这个自定义）
        signInfo.put("isProxySign", "0");// 是否代签   (0：不代签；1：代签；默认为 0)
        signInfos.add(signInfo);

        // CFC87AC1698336B6E05311016B0A9BC8  北京扫码付 另一方
        // CFC5D50666BE219BE05311016B0A4D22  北京扫码付

        signInfo = new JSONObject();
        signInfo.put("userId", "CFC87AC1698336B6E05311016B0A9BC8");// userid  开户时返回的
        signInfo.put("authorizationTime", getTxTime());// 获取验证码时间
        signInfo.put("location", "127.0.0.1");// IP地址
        signInfo.put("signLocation", "Signature2");// 签名域的标签值
        signInfo.put("projectCode", "123");// 项目编号， （项目编号这个自定义）
        signInfo.put("isProxySign", "0");// 是否代签   (0：不代签；1：代签；默认为 0)
        signInfos.add(signInfo);

        createContract.put("signInfos", signInfos);
        createContract.put("isSign", "0");// 签署类型,易生自身是否签署   0:抄送  1:签署  2:暂不签署  默认为 0， 要注意的是，如果易生不参与合同签署，这里需要传0，不然即使合同双方都签署了，合同的状态也不会变为已完成
//		createContract.put("signLocation", "Signature1");// 易生签名域的标签值
        contractBody.put("createContract", createContract);
        map.put("contractBody", contractBody.toJSONString());
        String sign = SignUtil.getSign(map, key);
        map.put("sign", sign);
        System.out.println("请求参数=====>" + map.toString());
        try {
            String str = HttpConnectUtils.sendHttpSRequest(url ,map, "POST", null);
            if (!StringUtils.isBlank(str)) {
                JSONObject json = JSON.parseObject(str);
                String sign1 = json.getString("sign");
                json.remove("sign");
                String sign2 = SignUtil.getSign((Map) json, key);
                System.out.println("sign2=====>" + sign2);
                if (sign2.equals(sign1)) {
                    System.out.println("验签成功");
                } else {
                    System.out.println("验签失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 签署合同 (多方 都有签署， 所以要调用多边)
    public static void test5() {
        Map<String, String> map = publicParam();
        map.put("txCode", "3206");
        JSONObject contractBody = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("txTime", getTxTime());
        contractBody.put("head", head);
        JSONObject signContract = new JSONObject();
        signContract.put("contractNo", "ZY20211108000000003");// 创建合同返回
        JSONObject signInfo = new JSONObject();
        signInfo.put("userId", "CFC5D50666BE219BE05311016B0A4D22");// 开户时返回
        signInfo.put("authorizationTime", getTxTime());// 输入验	证码的时间
        signInfo.put("location", "127.0.0.1");
        signInfo.put("projectCode", "123");
//		signInfo.put("isCheckProjectCode", isCheckProjectCode);
        signInfo.put("signLocation", "Signature1");// 签名域
        signContract.put("signInfo", signInfo);
        contractBody.put("signContract", signContract);
        map.put("contractBody", contractBody.toJSONString());
        String sign = SignUtil.getSign(map, key);
        map.put("sign", sign);
        System.out.println("请求参数=====>" + map.toString());
        try {
            String str = HttpConnectUtils.sendHttpSRequest(url ,map, "POST", null);
            if (!StringUtils.isBlank(str)) {
                JSONObject json = JSON.parseObject(str);
                String sign1 = json.getString("sign");
                json.remove("sign");
                String sign2 = SignUtil.getSign((Map) json, key);
                System.out.println("sign2=====>" + sign2);
                if (sign2.equals(sign1)) {
                    System.out.println("验签成功");
                } else {
                    System.out.println("验签失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 合同查询
    public static void test6() {
        Map<String, String> map = publicParam();
        map.put("txCode", "3210");
        JSONObject contractBody = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("txTime", getTxTime());
        contractBody.put("head", head);
        JSONObject contract = new JSONObject();
        contract.put("contractNo", "ZY20211108000000003");// 创建合同时返回
        contractBody.put("contract", contract);
        map.put("contractBody", contractBody.toJSONString());
        String sign = SignUtil.getSign(map, key);
        map.put("sign", sign);
        System.out.println("请求参数=====>" + map.toString());
        try {
            String str = HttpConnectUtils.sendHttpSRequest(url ,map, "POST", null);
            if (!StringUtils.isBlank(str)) {
                JSONObject json = JSON.parseObject(str);
                String sign1 = json.getString("sign");
                json.remove("sign");
                String sign2 = SignUtil.getSign((Map) json, key);
                System.out.println("sign2=====>" + sign2);
                if (sign2.equals(sign1)) {
                    System.out.println("验签成功");
                } else {
                    System.out.println("验签失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 合同下载
    public static void test7() {
        Map<String, String> map = publicParam();
        String contractNo = "ZY20211105000000004";
        map.put("contractNo", contractNo);// 创建合同时返回
        String sign = SignUtil.getSign(map, key);
        map.put("sign", sign);
        System.out.println("请求参数=====>" + map.toString());
        try {
            String downLoadUrl = "https://notify-test.eycard.cn:7443/EasypayMPSystem/DownloadContractServet.do";
            String str = HttpConnectUtils.sendHttpSRequest(downLoadUrl ,map, "POST", null);
            if (!StringUtils.isBlank(str)) {
                JSONObject json = JSON.parseObject(str);
                String sign1 = json.getString("sign");
                String base64sString = json.getString("pdfFileData");
                json.remove("sign");
                json.remove("pdfFileData");
                System.out.println(json.toString());
                String sign2 = SignUtil.getSign((Map) json, key);
                System.out.println("sign2=====>" + sign2);
                if (sign2.equals(sign1)) {
                    System.out.println("验签成功");
                } else {
                    System.out.println("验签失败");
                }

                String filePath = "C:\\Users\\Easypay\\Desktop\\easypay" + contractNo + ".pdf";
                Base64Tool.base64StringToPDF(base64sString, filePath);
                System.out.println("导出成功：" + filePath );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
